import FundCategory from "../models/FundCategory"
import { get } from "../utils/http"
const iconv = require('iconv-lite')
const cheerio = require('cheerio')

interface FundCategoryType {
  fund_code: string;
  fund_name: string;
}

// 获取单个基金的code和name
function getOneFundItem(text: string): FundCategoryType {
  const a: string[] = text.split('）')
  const fund_code: string = a[0].split('（')[1]
  const fund_name: string = a[1]
  return { fund_code, fund_name }
}

function formateDataSource(body: any) {
  // 将请求到的网页装载到jquery选择器中
  const $ = cheerio.load('<body>'+body+'</body>');
  const liList = $("body").find('.num_right').find("li")
  const fundList = [];
  liList.each((index, item) => {
    const targetA = $(item).find('a')[0]
    const aText = $(targetA).text()
    if (getOneFundItem(aText).fund_code) {
      fundList.push(getOneFundItem(aText))
    }
  })
  if (fundList.length > 0) {
    FundCategory.create(fundList, (err) => {
      if (!err) {
        console.log('数据插入成功')
      } else {
        console.log(err)
      }
    })
  }
}

function requestGetData() {
  // 获取请求之后的字符串
  const targetUrl = 'http://fund.eastmoney.com/allfund.html';
  get(targetUrl).then(body => {
    const buf =  iconv.decode(body, 'gb2312');
    formateDataSource(buf)
  })
}

export default requestGetData